import axios, { AxiosInstance } from "axios";
import { useStore as useUserStore } from "@/store/user";
import _ from "lodash";
import { message, notification } from "ant-design-vue";
import router from "@/router";

// 登录失效，弹窗提示
const logoutTips = _.debounce(() => {
  message.error("登录已失效请重新登录");
  const userStore = useUserStore();
  userStore.init();
  router.push(`/login`);
}, 5000, { leading: true, trailing: false })

export default class http {
  // 定义请求实例
  defineInstance(): AxiosInstance {
    const instance = axios.create();
    instance.defaults.baseURL = process.env.VUE_APP_BASE_API;
    // 请求拦截添加公共参数
    instance.interceptors.request.use((config: any) => {
      config.timeout = 100000;
      return config;

    })
    // 回传拦截处理回传内容
    instance.interceptors.response.use((response: any) => {
      return this.dealResponse(response);
    }, (error: any) => {
      console.error(error);
      let { message: msg } = error;
      if (msg == "Network Error") {
        msg = "后端接口连接异常";
      } else if (msg.includes("timeout")) {
        msg = "系统接口请求超时";
      } else if (msg.includes("Request failed with status code")) {
        msg = "系统接口" + msg.substr(msg.length - 3) + "异常";
      }
      message.error(msg, 5);
      return Promise.reject(error)
    })
    return instance;
  }
  // 处理回传数据
  dealResponse(response) {
    const code = response?.data?.code || null;
    const msg = response?.data?.msg || "";
    if (code === 200) {
      return response;
    } else if (code === 401) {
      logoutTips();
      return Promise.reject(response);
    } else if (code === 400) {
      message.error(msg);
      return Promise.reject(response);
    } else if (code === 500) {
      message.error(msg || '系统错误!');
      return Promise.reject(response);
    } else if (code === 601) {
      message.warning(msg);
      return Promise.reject(response);
    } else if (code) {
      // 未定义错误特殊报错方式
      notification.error({
        message: '错误提示',
        description: msg,
      })
      return Promise.reject(response);
    } else {
      // 没有code,默认为成功状态
      return response;
    }
  }
  // get请求
  get({
    url,
    data = {},
    header = {},
    needToken = true,
  }: {
    url: string,
    data?: any,
    header?: { [key: string]: any },
    needToken?: boolean,
  }) {
    const instance = this.defineInstance();
    instance.interceptors.request.use((config: any) => {
      if (needToken) {
        const userStore = useUserStore();
        const token = userStore.info.token || '';
        let Authorization: any = `Bearer ${token}`;
        config.headers.Authorization = Authorization;
      }
      Object.entries(header).forEach(item => {
        config.headers[item[0]] = item[1];
      })
      return config;
    });
    return instance.get(url, { params: data });
  }
  // post请求
  post({
    url,
    data = {},
    header = {},
    needToken = true,
  }: {
    url: string,
    data: any,
    header?: { [key: string]: any },
    needToken?: boolean,
  }) {
    const instance = this.defineInstance();
    instance.interceptors.request.use((config: any) => {
      if (needToken) {
        const userStore = useUserStore();
        const token = userStore.info.token || '';
        let Authorization: any = `Bearer ${token}`;
        config.headers.Authorization = Authorization;
      }
      Object.entries(header).forEach(item => {
        config.headers[item[0]] = item[1];
      })
      return config;
    });
    return instance.post(url, data);
  }
  // delete请求
  delete({
    url,
    needToken = true,
  }: {
    url: string,
    needToken?: boolean,
  }) {
    const instance = this.defineInstance();
    instance.interceptors.request.use((config: any) => {
      if (needToken) {
        const userStore = useUserStore();
        const token = userStore.info.token || '';
        let Authorization: any = `Bearer ${token}`;
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    return instance.delete(url);
  }
  // put请求
  put({
    url,
    data = {},
    header = {},
    needToken = true,
  }: {
    url: string,
    data: any,
    header?: { [key: string]: any },
    needToken?: boolean,
  }) {
    const instance = this.defineInstance();
    instance.interceptors.request.use((config: any) => {
      if (needToken) {
        const userStore = useUserStore();
        const token = userStore.info.token || '';
        let Authorization: any = `Bearer ${token}`;
        config.headers.Authorization = Authorization;
      }
      Object.entries(header).forEach(item => {
        config.headers[item[0]] = item[1];
      })
      return config;
    });
    return instance.put(url, data);
  }
}